package com.itany.homework.demo2;

import com.itany.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Author:石小俊
 * Date: 2022/11/4 16:33
 */
public class ObjectFactory {

    // 所有的对象交给工厂来创建
    // 在beans.properties中存储对象信息
    // 数据格式为:key=包名.类名
//    private static Properties p;
//    static{
//        p = new Properties();
//        try {
//            p.load(ObjectFactory.class.getClassLoader().getResourceAsStream("com/itany/homework/demo2/beans.properties"));
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
//        }
//
//    }
//
//    public static Object getObject(String key){
//        String value = p.getProperty(key);
//        try {
//            Object obj = Class.forName(value).newInstance();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//    }


    private static Map<String,Object> objs;
    static{
        objs = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader( ObjectFactory
                            .class
                            .getClassLoader()
                            .getResourceAsStream("com/itany/homework/demo2/beans.properties")));
            String line = null;
            while((line = br.readLine()) != null){
                if(!ParameterUtil.isNull(line)){
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    objs.put(key,Class.forName(value).newInstance());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }
    }

    public static Object getObject(String key){
        Object obj = objs.get(key);
        if(null == obj){
            System.out.println("根据key:"+key+"在配置文件中没有找到对应的配置");
            return null;
        }
        return obj;
    }
}
